package cn.peach.pet.service.impl;

import cn.peach.basic.exception.MyException;
import cn.peach.basic.service.impl.BaseServiceImpl;
import cn.peach.pet.domain.Pet;
import cn.peach.pet.domain.PetDetail;
import cn.peach.pet.mapper.PetDetailMapper;
import cn.peach.pet.mapper.PetMapper;
import cn.peach.pet.service.IPetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class PetServiceImpl  extends BaseServiceImpl<Pet> implements IPetService {

    @Autowired
    private PetMapper petMapper;
    @Autowired
    private PetDetailMapper petDetailMapper;

    @Override
    public void insert(Pet pet) {
        // 先pet 再返回自增主键
        petMapper.add(pet);
        PetDetail detail = pet.getDetail();
        detail.setPet_id(pet.getId());
        petDetailMapper.add(detail);
    }

    /**
     * 查询详情
     * @param id
     * @return
     */
    @Override
    public Pet selectOnlineById(Long id) {
        // 详情是在线上展示的
        return petMapper.selectByIdAndState(id,Pet.STATE_ONLINE);
    }

    /**
     * 上架
     * @param ids
     */
    @Override
    public void publish(List<Long> ids) {
        if (ids == null || ids.size() == 0){
            throw new MyException("上架请求错误");
        }
        // 下架状态才能上架
        List<Pet> pets = petMapper.patchSelectById(ids, Pet.STATE_OFFLINE);
        Date date2 = new Date();
        // 修改状态
        pets.forEach(pet ->{
            pet.setState(Pet.STATE_OFFLINE);
            pet.setOffsaletime(date2);
            petMapper.update(pet);
        });
    }

    /**
     * offsaletime
     * onsaletime
     * @param ids
     * @param state
     */
    @Override
    public void onsale(List<Long> ids, Integer state) {
        petMapper.updateOnsaleById(ids, "onsaletime", state);
    }

    /**
     * 下架
     * @param ids
     */
    @Override
    public void offSale(List<Long> ids,Integer state) {
        // 参数的非空判断
        if (ids == null || ids.size() == 0){
            throw new MyException("下架请求错误");
        }
        // 批量查询宠物数据列表  要下架就必须是上架状态才能下架 这里就查询上架的数据
        List<Pet> petList = petMapper.patchSelectById(ids,Pet.STATE_ONLINE);
        Date date = new Date();
        // 要下架就把状态改为OFFLINE
        petList.forEach(pet ->{
            pet.setState(Pet.STATE_OFFLINE);
            pet.setOffsaletime(date);
            petMapper.update(pet);
        });

    }
}
